<script setup>
import { ref, onMounted, onBeforeUnmount, watch, toRefs } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
})

const chartRef = ref(null)
let chart = null

const { data } = toRefs(props)

const initChart = () => {
  if (!chartRef.value) return

  // 销毁旧的实例
  if (chart) {
    chart.dispose()
  }

  chart = echarts.init(chartRef.value)

  setOptions()
}

const setOptions = () => {
  console.log(data.value)
  const option = {
    title: {
      text: '磁盘调度移动图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: Array.from(
        { length: data.value?.path.length },
        (_, i) => `步骤${i}`
      )
    },
    yAxis: {
      type: 'value',
      name: '柱面号',
      min: 0,
      max: 199
    },
    series: [
      {
        data: data.value?.path,
        type: 'line',
        smooth: false
      }
    ]
  }
  chart.setOption(option)
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})

watch(
  () => data,
  () => {
    setOptions()
  },
  { deep: true }
)
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 40rem"></div>
</template>
